<?php

namespace app\common\model;

use think\Db;
use think\Model;


class Commission extends Model
{

    

    

    // 表名
    protected $name = 'commission';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_time_text',
	    'status_text'
    ];
    
	const STATUS_WAIT = 0;
	const STATUS_Y = 1;
	const STATUS_CANCEL = 2;
	
	public static $statusList = [
		self::STATUS_Y => '已发放',
		self::STATUS_WAIT => '待发放',
		self::STATUS_CANCEL => '已取消'
	];
    
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ??'';
	}


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
	
	public function user() {
		return $this->belongsTo('user', 'user_id',  'id', '', 'left')->setEagerlyType(0);
	}
	
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id',  'id', '', 'left')->setEagerlyType(0);
	}
	
	public function relationuser() {
		return $this->belongsTo('user', 'relation_user_id',  'id', '', 'left')->setEagerlyType(0);
	}
	
	
	/**
	 * 添加返利记录
	 * @param $userId 用户ID
	 * @param $relationUserId 关联用户ID
	 * @param $orderId 订单ID
	 * @param $goodsId
	 * @param $orderGoodsId
	 * @param $amount
	 * @return false|int
	 */
	public function addRow($userId, $relationUserId, $orderId, $goodsId, $orderGoodsId, $amount) {
		$res = $this->isUpdate(false)
			->save([
				'user_id' => $userId,
				'relation_user_id' => $relationUserId,
				'order_id' => $orderId,
				'goods_id' => $goodsId,
				'order_goods_id' => $orderGoodsId,
				'amount' => $amount,
				'status' => self::STATUS_WAIT
			]);
		return $res;
	}
	
	/**
	 * 订单返利
	 * @param $orderId
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function rebate($orderId) {
		$where = ['order_id' => $orderId, 'status' => self::STATUS_WAIT];
		$rows = $this->where($where)->select();
		
		if($rows) {
			
			$res = $this->save(['status' => self::STATUS_Y], $where);
			if(!$res) {
				$this->error = '更改佣金记录状态出错';
				return false;
			}
			
			$fundsModel = new Funds();
			
			foreach ($rows as $row) {
				//添加用户金额
				$user = User::get($row['user_id']);
				$userRes = Db::name('user')
					->where(['id' => $row['user_id']])
					->setInc('money', $row['amount']);
				if(!$userRes) {
					$this->error = '添加用户金额出错';
					return false;
				}
				
				$fundsRes = $fundsModel->addRecord($row['user_id'], $row['amount'], $user['money'], $fundsModel::ACCOUNT_TYPE_BALANCE, $fundsModel::OPE_TYPE_PLUS, $fundsModel::TYPE_REBATE, $row['order_id'],'', $row['relation_user_id']);
				if(!$fundsRes) {
					$this->error = '添加资金记录出错';
				return false;
				}
			}
		}
		
		return true;
	}
}
